<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\PageRequest;
use App\Models\Application\Application;
use App\Models\Application\Page;
use App\Repositories\Application\PageRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class PageController extends Controller
{
    use ModelForm;

    /** @var  PageRepository */
    private $pageRepository;

    public function __construct(PageRepository $pageRepo)
    {
        $this->pageRepository = $pageRepo;
    }

    /**
     * Display a listing of the Page.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.pages.index_header'));
            $content->description(__('application.pages.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Page.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.pages.create_header'));
            $content->description(__('application.pages.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Page in storage.
     *
     * @param PageRequest $request
     *
     * @return Response
     */
    public function store(PageRequest $request)
    {
        $input = $request->all();
        // 单个页面只能对应单个布局
        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.page');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['ui'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $page = $this->pageRepository->create($input);

        // if ($page) {
        //     if (is_array($request->get('layouts'))) {
        //         $page->layouts()->sync(array_filter($request->get('layouts')));
        //     }
        // }
        // 插入页面布局中间表
        // DB::table('page_layouts')->insert(['page_id' => $page->id, 'layout_id' => $input['layout_id']]);
        Flash::success(__('application.pages.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.pages.index'));

    }

    /**
     * Display the specified Page.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $page = $this->pageRepository->findWithoutFail($id);

        if (empty($page)) {
            Flash::error(__('application.pages.not_found'));

            return redirect(route('application.pages.index'));
        }

        return view('application.pages.show')->with('page', $page);

    }

    /**
     * Show the form for editing the specified Page.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.pages.edit_header'));
            $content->description(__('application.pages.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Page in storage.
     *
     * @param  int              $id
     * @param PageRequest $request
     *
     * @return Response
     */
    public function update($id, PageRequest $request)
    {
        $page = $this->pageRepository->findWithoutFail($id);
        if (empty($page)) {
            Flash::error(__('application.pages.not_found'));
            return redirect(route('application.pages.index'));
        }

        // 单个页面只能对应单个布局
        // if (count(array_filter($request->get('layouts'))) > 1) {
        //     Flash::error('失败,一个页面只能选择一个布局!');
        //     return redirect(route('application.pages.index'));
        // }
        $input = $request->all();

        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.page');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath    = $rootDir . '/' . $dir . '/' . $newImageName;
                $input['ui'] = $fullPath;
                $bool        = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $page = $this->pageRepository->update($input, $id);
        // if ($page) {
        //     if (is_array($request->get('layouts'))) {
        //         $page->layouts()->sync(array_filter($request->get('layouts')));
        //     }
        // }

        // 插入页面布局中间表
        // DB::table('page_layouts')->where('page_id',$id)->delete();
        // DB::table('page_layouts')->insert(['page_id' => $id, 'layout_id' => $input['layout_id']]);
        Flash::success(__('application.pages.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.pages.index'));
    }

    /**
     * Remove the specified Page from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->pageRepository->batchDelete('id', $id)) {
                DB::table('page_layouts')->whereIn('page_id', $id)->delete();

                return response()->json(['message' => __('application.pages.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $page = $this->pageRepository->findWithoutFail($id);

        if (empty($page)) {
            Flash::error(__('application.pages.not_found'));

            return redirect(route('application.pages.index'));
        }

        if ($flag = $this->pageRepository->delete($id)) {
            DB::table('page_layouts')->where('page_id', $id)->delete();

            // $page->applications()->detach();
            return response()->json(['message' => __('application.pages.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Page::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '页面名称');
            $form->textarea('descrition', '页面描述');
            $form->image('ui', 'UI')->removable();
            // $layouts = \App\Models\Application\Layout::pluck('name', 'id')->toArray();
            // $form->multipleSelect('layouts', 'layouts选择')->options($layouts)->help('一个页面只能选择一个layout布局');
            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Page::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.pages.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.pages.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.pages.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.pages.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.pages.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.pages.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {

                // $id = $actions->getKey();
                // // 页面详情按钮
                // $url = route('application.applications.application_details', ['application_id' => $id]);
                // $actions->prepend('<a href ="' . $url . '" title="页面布局管理"><i class="fa fa-list"></i></a>');

                // 编辑按钮
                if (Admin::user()->cannot('application.pages.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.pages.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.pages.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.pages.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '页面名称')->sortable();
            $grid->column('descrition', '页面描述')->sortable();
            // $grid->layouts('layouts布局')->pluck('name')->label();
            $uploadConfig = config('custom.base.upload.page');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('ui', 'UI')->image($host);

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '页面名称');

            });
        });
    }

    /**
     * 剧集文件crud
     */
    /**
     * Display a listing of the Vifile.
     *
     * @return Response
     */
    public function applicationIndex($application_id)
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.pages.index_header'));
            $content->description(__('application.pages.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Vifile.
     *
     * @return Response
     */
    public function applicationCreate($application_id)
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.pages.create_header'));
            $content->description(__('application.pages.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Vifile in storage.
     *
     * @param VifileRequest $request
     *
     * @return Response
     */
    public function applicationStore($application_id, PageRequest $request)
    {
        // 新建的时候和剧集关联
        if (!$application = Application::find($application_id)) {
            Flash::error('应用不能为空!');
            return redirect(route('application.pages.index'));
        }
        // 单个页面只能对应单个布局
        if (count(array_filter($request->get('layouts'))) > 1) {
            Flash::error('失败,一个页面只能选择一个布局!');
            return redirect(route('application.applications.application_details', ['application_id' => $application_id]));
        }
        $input = $request->all();
        $page  = $this->pageRepository->create($input);
        $application->pages()->save($page);
        // 插入页面布局中间表
        // DB::table('page_layouts')->insert(['page_id' => $page->id, 'layout_id' => $input['layout_id']]);
        if ($page) {
            if (is_array($request->get('layouts'))) {

                $page->layouts()->sync(array_filter($request->get('layouts')));
            }
        }
        Flash::success(__('application.pages.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.applications.application_details', ['application_id' => $application_id]));

    }

    /**
     * Show the form for editing the specified Vifile.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function applicationEdit($application_id, $id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.pages.edit_header'));
            $content->description(__('application.pages.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Vifile in storage.
     *
     * @param  int              $id
     * @param VifileRequest $request
     *
     * @return Response
     */
    public function applicationUpdate($application_id, $id, Request $request)
    {

        $sValidators = [
            'name' => 'max:100',
        ];
        $validators = [];

        $input = $request->all();
        // 判断是否行内编辑
        $input = $this->handleEditable($input);

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }
        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'name' => '名称',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $page = $this->pageRepository->findWithoutFail($id);

        if (empty($page)) {
            Flash::error(__('application.pages.not_found'));

            return redirect(route('application.pages.index'));
        }
        // 单个页面只能对应单个布局
        if (count(array_filter($request->get('layouts'))) > 1) {
            Flash::error('失败,一个页面只能选择一个布局!');
            return redirect(route('application.applications.application_details', ['application_id' => $application_id]));
        }
        $page = $this->pageRepository->update($input, $id);
        // DB::table('page_layouts')->where('page_id', $id)->delete();

        // 插入页面布局中间表
        // if ($page) {
        //     if (is_array($request->get('layouts'))) {
        //         $page->layouts()->sync(array_filter($request->get('layouts')));
        //     }
        // }
        // DB::table('page_layouts')->insert(['page_id' => $id, 'layout_id' => $input['layout_id']]);
        Flash::success(__('application.pages.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.applications.application_details', ['application_id' => $application_id]));
    }

    /**
     * Remove the specified Vifile from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function applicationDestroy($application_id, $id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->pageRepository->batchDelete('id', $id)) {
                DB::table('page_layouts')->whereIn('page_id', $id)->delete();
                return response()->json(['message' => __('application.pages.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $page = $this->pageRepository->findWithoutFail($id);

        if (empty($page)) {
            Flash::error(__('application.pages.not_found'));

            return redirect(route('application.pages.index'));
        }

        if ($flag = $this->pageRepository->delete($id)) {

            DB::table('application_pages')->where(['page_id' => $id, 'application_id' => $application_id])->delete();
            DB::table('page_layouts')->where('page_id', $id)->delete();

            return response()->json(['message' => __('application.pages.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }
}
